package fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.boltshow.MainActivity;
import com.example.administrator.boltshow.R;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import application.MyApplication;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import model.User;

import static cn.smssdk.SMSSDK.getSupportedCountries;
import static cn.smssdk.SMSSDK.getVerificationCode;
import static cn.smssdk.SMSSDK.submitVerificationCode;

/**
 * Created by Administrator on 2016/8/30.
 */
public class RegisterFragment extends Fragment {
    private final String TAG="--MainActivity--";
    //app key和app secret 需要填自己应用的对应的！这里只是我自己创建的应用。
    private final String appKey="16ada9d35088a";
    private final String appSecret="383b3c45ea74e6ded5f5d889e0f5a8c3";
    private EventHandler eh;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 0:
                    if(!TextUtils.isEmpty(mEditTextPassword.getText().toString())) {
                        //客户端验证成功，可以进行注册,返回校验的手机和国家代码phone/country
                        //Toast.makeText(getActivity(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        User user = new User();
                        user.setUserNumber(mEditTextPhone.getText().toString());
                        user.setPassword(mEditTextPassword.getText().toString());
                        try {
                            mDb.save(user);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        Toast.makeText(getActivity(), "注册成功,请登录", Toast.LENGTH_SHORT).show();

                    }
                    else {
                        Toast.makeText(getActivity(), "密码不能为空", Toast.LENGTH_SHORT).show();
                    }

                    break;
                case 1:
                    //获取验证码成功
                    Toast.makeText(getActivity(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    //返回支持发送验证码的国家列表
                    Toast.makeText(getActivity(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //View控件
    private Button bt_getCode;
    private Button bt_vertify;
    //手机号码
    private String phone;
    //验证码
    private String code;

    private boolean isChange;
    //控制按钮样式是否改变
    private boolean tag = true;
    //每次验证请求需要间隔60S
    private int i=60;

    private EditText mEditTextPhone;
    private EditText mEditTextCode;
    private EditText mEditTextPassword;

    private DbManager mDb;
    private MyApplication mApp;

    private CheckBox cbShow;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.register_fragment,null);

        DbManager.DaoConfig config = new DbManager.DaoConfig();
        mDb = x.getDb(config);
        mApp = (MyApplication) getActivity().getApplication();

        // 启动短信验证sdk
        SMSSDK.initSDK(getActivity(), appKey, appSecret);

        eh=new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Message msg = new Message();
                        msg.arg1 = 0;
                        msg.obj = data;
                        handler.sendMessage(msg);
                        Log.d(TAG, "提交验证码成功");
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Message msg = new Message();
                        //获取验证码成功
                        msg.arg1 = 1;
                        msg.obj = "获取验证码成功";
                        handler.sendMessage(msg);
                        Log.d(TAG, "获取验证码成功");
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        Message msg = new Message();
                        //返回支持发送验证码的国家列表
                        msg.arg1 = 2;
                        msg.obj = "返回支持发送验证码的国家列表";
                        handler.sendMessage(msg);
                        Log.d(TAG, "返回支持发送验证码的国家列表");
                    }
                } else {
                    Message msg = new Message();
                    //返回支持发送验证码的国家列表
                    msg.arg1 = 3;
                    msg.obj = "验证失败";
                    handler.sendMessage(msg);
                    Log.d(TAG, "验证失败");
                    ((Throwable) data).printStackTrace();
                }
            }
        };

        SMSSDK.registerEventHandler(eh); //注册短信回调

        bt_getCode= (Button) view.findViewById(R.id.bt_getCode);
        bt_getCode.setClickable(false);
        bt_vertify= (Button) view.findViewById(R.id.bt_register_login);
        mEditTextPhone = (EditText) view.findViewById(R.id.et_register_user);
        mEditTextCode = (EditText) view.findViewById(R.id.et_register_yanzheng);
        mEditTextPassword = (EditText) view.findViewById(R.id.et_register_password);
        cbShow = (CheckBox) view.findViewById(R.id.cb_register_show);
        cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mEditTextPassword.setInputType(EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    mEditTextPassword.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
                            | EditorInfo.TYPE_CLASS_TEXT);

                }
            }
        });

        bt_getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取验证码操作
                phone=mEditTextPhone.getText().toString();
                if(phone.equals("")){
                    Toast.makeText(getActivity(),"手机号不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    //填写了手机号码
                    if(isMobileNO(phone)){
                        //如果手机号码无误，则发送验证请求
                        bt_getCode.setClickable(true);
                        changeBtnGetCode();
                        getSupportedCountries();
                        getVerificationCode("86", phone);
                    }else{
                        //手机号格式有误
                        Toast.makeText(getActivity(),"手机号格式错误，请检查",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        bt_vertify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //验证操作
                code=mEditTextCode.getText().toString();
                if (code.equals("")){
                    Toast.makeText(getActivity(),"验证码不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    //填写了验证码，进行验证
                    submitVerificationCode("86", phone, code);
                }
            }
        });

        return view;
    }









    /*
  * 改变按钮样式
  * */
    private void changeBtnGetCode() {

        Thread thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        //如果活动为空
                        if (getActivity() == null) {
                            break;
                        }

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                bt_getCode.setText("(" + i + ")后能获取");
                                bt_getCode.setClickable(false);
                            }
                        });

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;

                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            bt_getCode.setText("获取验证码");
                            bt_getCode.setClickable(true);
                        }
                    });
                }
            }
        };
        thread.start();
    }

    private boolean isMobileNO(String phone) {
       /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(phone)) return false;
        else return phone.matches(telRegex);
    }

}
